package com.mbc.rmt.manager;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

import com.mbc.common.CommonSingleton;
import com.mbc.common.dao.CommonDAOFactory;
import com.mbc.common.dao.CurrencyRateDAO;
import com.mbc.common.dao.CurrencyRateDetailDAO;
import com.mbc.common.dao.LogDAO;
import com.mbc.common.entities.CurrencyRate;
import com.mbc.common.entities.Log;
import com.mbc.common.exception.DataDuplicationException;
import com.mbc.common.exception.DataNotFoundException;
import com.mbc.common.manager.AbstractMgr;
import com.mbc.common.utils.KeyGenerator;
import com.mbc.rmt.dao.AgentCOADAO;
import com.mbc.rmt.dao.AgentDAO;
import com.mbc.rmt.dao.BankDAO;
import com.mbc.rmt.dao.BranchBalanceDAO;
import com.mbc.rmt.dao.BranchCOADAO;
import com.mbc.rmt.dao.CashPaidToIndividualDAO;
import com.mbc.rmt.dao.General_COADAO;
import com.mbc.rmt.dao.RemittanceDAOFactory;
import com.mbc.rmt.data.CashPaidToIndividualDataList;
import com.mbc.rmt.entities.Bank;
import com.mbc.rmt.entities.BranchBalance;
import com.mbc.rmt.entities.Agent;
import com.mbc.rmt.entities.BranchCOA;
import com.mbc.rmt.entities.CashPaidToIndividual;
import com.mbc.rmt.entities.CashPaidToIndividualCri;
import com.mbc.rmt.entities.CashPaidToIndividualRpt;
import com.mbc.rmt.entities.GeneralLedger;
import com.mbc.rmt.entities.General_COA;
import com.mbc.rmt.manager.DefinePaymentTypeMgr.GL_STATUS;


public class CashPaidToIndividualMgr extends AbstractMgr{
	
	private CashPaidToIndividualDAO cashpaidtoindividualDAO;
	public static enum STATUS { ADD, UPDATE, DELETE }
	private BranchBalanceDAO branchbalanceDAO;
	private CurrencyRateDetailDAO currencyrateDetailDAO;
	private AgentCOADAO agentCOADAO;
	private AgentDAO agentDAO;
	private CurrencyRateDAO currencyRateDAO;
	private General_COADAO generalCOADAO;
	private BankDAO bankDAO;
	private BranchCOADAO branchCOADAO;
	private LogDAO logDAO;

	public CashPaidToIndividualMgr() {
	}
	
	public CashPaidToIndividualMgr(String sessionId) {
		this.sessionId = sessionId;
	}
	
	public String create(CashPaidToIndividual entity) throws Exception {
		openConnection();
		try {
			beginTransaction();
			cashpaidtoindividualDAO = RemittanceDAOFactory.getCashPaidToIndividualDetailDAO(dbManager.getConnection());
			currencyrateDetailDAO = CommonDAOFactory.getCurrencyRateDetailDAO(dbManager.getConnection());
			branchbalanceDAO = RemittanceDAOFactory.getBranchBalanceDAO(dbManager.getConnection());
			logDAO = CommonDAOFactory.getLogDAO(getConnection());
			String voucher = "";
			if(entity.getPaymentID() == 0){
				CashPaidToIndividual l_info = new CashPaidToIndividual();
				l_info = cashpaidtoindividualDAO.find(entity.getPaymentID());			
				if (l_info != null) {
					throw new Exception("Invoice ID already exists!");
				} else {
//					CurrencyRateDetail l_currencyrateDetail = new CurrencyRateDetail();					
//					l_currencyrateDetail = currencyrateDetailDAO.findLatest(entity.getCurrencyrateid());
//					
//					if (l_currencyrateDetail.getRate()  !=  entity.getRate()){					  
//				   
//					   l_currencyrateDetail.setCurrencyRateDetailId(KeyGenerator.generateKey(getConnection()));
//					   l_currencyrateDetail.setCurrencyRateId(entity.getCurrencyrateid());
//					   l_currencyrateDetail.setRate(entity.getRate());
//					   l_currencyrateDetail.seteDateTime(entity.getTrdate());
//					   currencyrateDetailDAO.create(l_currencyrateDetail);					
//					}
					UpdateCashPaid(STATUS.ADD,entity);
					voucher = RemittanceSerialMgr.getFormattedSerial(RemittanceSerialMgr.CASH_PAID_TO_INDIVIDUAL, entity.getTrdate(), entity.getDefaultbranchID(), getConnection());
					entity.setPaymentID(KeyGenerator.generateKey(getConnection()));
					entity.setPaymentno(voucher);
					gotoGL(entity, GL_STATUS.CREATE);
					cashpaidtoindividualDAO.create(entity);
					
					Log l_logentity = new Log();
					l_logentity.setTablename("CashPaidToIndividual");
					l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
					l_logentity.setKey(entity.getPaymentID());
					l_logentity.setUserid(entity.getUserid());
					l_logentity.setLogstatus(Log.__SAVE_DATA);
					logDAO.getData(l_logentity);
					
						BranchBalance l_balance = new BranchBalance();					
						l_balance.setCurrencyid(entity.getCurrencyID());
						if(entity.getFrombranchID() !=0)
						{	
							l_balance.setBranch_id(entity.getFrombranchID());
						}
						else
						{
							l_balance.setBranch_id(entity.getDefaultbranchID());
						}
						l_balance = branchbalanceDAO.getInfo(l_balance);					
						if(l_balance == null)
						{
							l_balance = new BranchBalance();
							l_balance.setBranchbalance_id(KeyGenerator.generateKey(getConnection()));
							if(entity.getFrombranchID() != null)
							{	
								l_balance.setBranch_id(entity.getFrombranchID());
							}
							else
							{
								l_balance.setBranch_id(entity.getDefaultbranchID());
							}
							
							l_balance.setCurrencyid(entity.getCurrencyID());
							l_balance.setOpeningbalance(0.0);
						
						l_balance.setCurrentbalance(entity.getAmount());
						branchbalanceDAO.create(l_balance);						
						}
						else
						{
							l_balance.setCurrentbalance(l_balance.getCurrentbalance() + entity.getAmount());
							branchbalanceDAO.update(l_balance);						
						}
					}
//					else if(entity.getFromagentID()!= 0)
//					{
//						AgentBalance l_agent = new AgentBalance();					
//						l_agent.setCurrencyid(entity.getCurrencyID());
//						l_agent.setAgent_id(entity.getFromagentID());
//						l_agent =agentbalanceDAO.getInfo(l_agent);					
//						
//						 if(l_agent == null)
//						{
//							l_agent = new AgentBalance();
//							l_agent.setAgentbalance_id(KeyGenerator.generateKey(getConnection()));
//							l_agent.setAgent_id(entity.getFromagentID());
//							l_agent.setCurrencyid(entity.getCurrencyID());
//							l_agent.setOpeningbalance(0.0);
//							
//							l_agent.setCurrentbalance(entity.getAmount());
//							agentbalanceDAO.create(l_agent);						
//						}
//						else
//						{
//							l_agent.setCurrentbalance(l_agent.getCurrentbalance() + entity.getAmount());
//							agentbalanceDAO.update(l_agent);						
//						}
//					}
//				}
			}
					
			
			else{
				
				cashpaidtoindividualDAO = RemittanceDAOFactory.getCashPaidToIndividualDetailDAO(dbManager.getConnection());
				gotoGL(entity, GL_STATUS.CREATE);
				UpdateCashPaid(STATUS.UPDATE,entity);
				cashpaidtoindividualDAO.update(entity);
				
				Log l_logentity = new Log();
				l_logentity.setTablename("CashPaidToIndividual");
				l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
				l_logentity.setKey(entity.getPaymentID());
				l_logentity.setUserid(entity.getUserid());
				l_logentity.setLogstatus(Log.__UPDATE_DATA);
				logDAO.getData(l_logentity);
				
//				CurrencyRateDetail l_currencyrateDetail = new CurrencyRateDetail();					
//				l_currencyrateDetail = currencyrateDetailDAO.findLatest(entity.getCurrencyrateid());
//				
//				if (l_currencyrateDetail.getRate()  !=  entity.getRate()){					  
//			   
//				   l_currencyrateDetail.setCurrencyRateDetailId(KeyGenerator.generateKey(getConnection()));
//				   l_currencyrateDetail.setCurrencyRateId(entity.getCurrencyrateid());
//				   l_currencyrateDetail.setRate(entity.getRate());
//				   l_currencyrateDetail.seteDateTime(entity.getTrdate());
//				   currencyrateDetailDAO.create(l_currencyrateDetail);					
//				}				
				
				BranchBalance l_balance = new BranchBalance();

				double npamt = 0;
				double tempnpamt = 0;
				CashPaidToIndividual temp_entity = new CashPaidToIndividual();
				temp_entity = cashpaidtoindividualDAO.getCashPaidToIndividual(entity);
				npamt = entity.getAmount();	
				tempnpamt =  temp_entity.getAmount();
				long currencyid = entity.getCurrencyID();
				long tempcurrencyid = temp_entity.getCurrencyID();
				long branchid = entity.getFrombranchID();
				
				long tempbranchid = temp_entity.getFrombranchID();
				long defaultbranchid = entity.getDefaultbranchID();
				long tempdefaultbranchid = temp_entity.getDefaultbranchID();
				if(entity.getFrombranchID() != 0)
				{
					if(tempcurrencyid == currencyid &&  tempbranchid == branchid)
					{
						l_balance.setCurrencyid(entity.getCurrencyID());
						l_balance.setBranch_id(entity.getFrombranchID());
							
						l_balance = branchbalanceDAO.getInfo(l_balance);
																			
						double amt = 0;
						
						if(npamt > tempnpamt){
							amt = tempnpamt - npamt;
							
								
								l_balance.setCurrentbalance(l_balance.getCurrentbalance() + amt);
						}
						else if(npamt < tempnpamt){										
							amt = tempnpamt - npamt;
							
								l_balance.setCurrentbalance(l_balance.getCurrentbalance() + amt);					
						}
						else{
							l_balance.setCurrentbalance(l_balance.getCurrentbalance());
						}
					}
					else
					{
						double amount = 0;
						l_balance.setCurrencyid(entity.getTempcurrencyid());
						l_balance.setBranch_id(entity.getTempbranchid());
						l_balance = branchbalanceDAO.getInfo(l_balance);	
						
			
							amount = l_balance.getCurrentbalance() + tempnpamt;
						
						l_balance.setOpeningbalance(amount);
						l_balance.setCurrentbalance(amount);
						branchbalanceDAO.update(l_balance);
						
						l_balance.setCurrencyid(entity.getCurrencyID());
						l_balance.setBranch_id(entity.getFrombranchID());
						l_balance = branchbalanceDAO.getInfo(l_balance);
											
						if(l_balance == null)
						{						
							l_balance = new BranchBalance();
							l_balance.setBranchbalance_id(KeyGenerator.generateKey(getConnection()));
							l_balance.setBranch_id(entity.getFrombranchID());
							l_balance.setCurrencyid(entity.getCurrencyID());
							l_balance.setOpeningbalance(0.0);
							l_balance.setCurrentbalance(npamt);
							
							branchbalanceDAO.create(l_balance);
						
						}
						else
						{
								if(entity.getTempcurrencyid() == entity.getCurrencyID() && entity.getTempbranchid() == entity.getFrombranchID())
								{
											
										l_balance.setCurrentbalance(amount - npamt);
								}
								else{		
										
										l_balance.setCurrentbalance(l_balance.getCurrentbalance() - npamt);
									}
						}
							
							
					}
					branchbalanceDAO.update(l_balance);			
			}
			else
			{
				if(tempcurrencyid == currencyid &&  tempdefaultbranchid == defaultbranchid)
				{
					l_balance.setCurrencyid(entity.getCurrencyID());
					l_balance.setBranch_id(entity.getDefaultbranchID());
						
					l_balance = branchbalanceDAO.getInfo(l_balance);
																		
					double amt = 0;
					
					if(npamt > tempnpamt){
						amt = tempnpamt - npamt;
						
							
							l_balance.setCurrentbalance(l_balance.getCurrentbalance() + amt);
					}
					else if(npamt < tempnpamt){										
						amt = tempnpamt - npamt;
						
							l_balance.setCurrentbalance(l_balance.getCurrentbalance() + amt);					
					}
					else{
						l_balance.setCurrentbalance(l_balance.getCurrentbalance());
					}
				}
				else
				{
					double amount = 0;
					l_balance.setCurrencyid(entity.getTempcurrencyid());
					l_balance.setBranch_id(entity.getTempdefaultbranchid());
					l_balance = branchbalanceDAO.getInfo(l_balance);	
					
		
						amount = l_balance.getCurrentbalance() + tempnpamt;
					
					l_balance.setOpeningbalance(amount);
					l_balance.setCurrentbalance(amount);
					branchbalanceDAO.update(l_balance);
					
					l_balance.setCurrencyid(entity.getCurrencyID());
					l_balance.setBranch_id(entity.getDefaultbranchID());
					l_balance = branchbalanceDAO.getInfo(l_balance);
										
					if(l_balance == null)
					{						
						l_balance = new BranchBalance();
						l_balance.setBranchbalance_id(KeyGenerator.generateKey(getConnection()));
						l_balance.setBranch_id(entity.getDefaultbranchID());
						l_balance.setCurrencyid(entity.getCurrencyID());
						l_balance.setOpeningbalance(0.0);
						l_balance.setCurrentbalance(npamt);
						
						branchbalanceDAO.create(l_balance);
					
					}
					else
					{
							if(entity.getTempcurrencyid() == entity.getCurrencyID() && entity.getTempdefaultbranchid() == entity.getDefaultbranchID()){
										
									l_balance.setCurrentbalance(amount - npamt);
								}
								else{		
									
									l_balance.setCurrentbalance(l_balance.getCurrentbalance() - npamt);
								}
						}
						
						
				}
				branchbalanceDAO.update(l_balance);		
			}
					
			}	
			commintTransaction();
			return voucher;
		} catch (SQLException e) {
			if (DataDuplicationException.UNIQUE_KEY_ERROR_CODE == e
					.getErrorCode())
				throw new DataDuplicationException(e.getMessage());
			else
				rollbackTransaction();
	 		throw e;
		} finally {
			closeConnection();
		}
	}
	

	public void update(CashPaidToIndividual entity) throws Exception {
		openConnection();
		try {
	
		} finally {
			closeConnection();
		}
	}

	public void delete(CashPaidToIndividual entity,long userId, Date deletedDate) throws Exception {
		openConnection();
		try {
			cashpaidtoindividualDAO = RemittanceDAOFactory.getCashPaidToIndividualDetailDAO(dbManager
					.getConnection());
			branchbalanceDAO = RemittanceDAOFactory.getBranchBalanceDAO(dbManager.getConnection());
			
			logDAO = CommonDAOFactory.getLogDAO(getConnection());
			Log l_logentity = new Log();
			l_logentity.setTablename("CashPaidToIndividual");
			l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
			l_logentity.setKey(entity.getPaymentID());
			l_logentity.setUserid(userId);
			l_logentity.setLogstatus(Log.__DELETE_DATA);
			logDAO.getData(l_logentity);
			
			UpdateCashPaid(STATUS.DELETE,entity);
			cashpaidtoindividualDAO.delete(entity);
//			AgentBalance l_agent = new AgentBalance();
//			l_agent.setCurrencyid(entity.getCurrencyID());
//			l_agent.setAgent_id(entity.getDefaultbranchID());
//			l_agent = agentbalanceDAO.getInfo(l_agent);
//			if(l_agent != null)
//			{
//				l_agent.setAgent_id(entity.getDefaultbranchID());
//				l_agent.setCurrencyid(entity.getCurrencyID());
//				l_agent.setCurrentbalance(l_agent.getCurrentbalance()-entity.getAmount());
//				agentbalanceDAO.update(l_agent);
//			}
			
			BranchBalance l_balance = new BranchBalance();
			l_balance.setCurrencyid(entity.getCurrencyID());
			if(entity.getFrombranchID() != 0)
			{
				l_balance.setBranch_id(entity.getFrombranchID());
			}
			else
			{
				l_balance.setBranch_id(entity.getDefaultbranchID());
			}
			l_balance = branchbalanceDAO.getInfo(l_balance);
			
			if(l_balance != null){
				if(entity.getFrombranchID() != 0)
				{
					l_balance.setBranch_id(entity.getFrombranchID());
				}
				else
				{
					l_balance.setBranch_id(entity.getDefaultbranchID());
				}
				l_balance.setCurrencyid(entity.getCurrencyID());
				l_balance.setCurrentbalance(l_balance.getCurrentbalance()- entity.getAmount());			
				branchbalanceDAO.update(l_balance);
				gotoGL(entity, GL_STATUS.DELETE);
				//GoToAgentBalance(STATUS.DELETE, entity);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}

	public CashPaidToIndividualDataList findCashPaidDataList(CashPaidToIndividual cri)
			throws Exception {
		openConnection();
		try {

			cashpaidtoindividualDAO = RemittanceDAOFactory.getCashPaidToIndividualDetailDAO(dbManager
				.getConnection());
			return cashpaidtoindividualDAO.findCashPaidToIndividualList(cri);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}	

	public CashPaidToIndividual getCashPaidToIndividual(CashPaidToIndividual cashpaid) throws Exception {
		openConnection();
		try {
			cashpaidtoindividualDAO = RemittanceDAOFactory.getCashPaidToIndividualDetailDAO(dbManager
					.getConnection());
			return cashpaidtoindividualDAO.getCashPaidToIndividual(cashpaid);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}	

	public ArrayList<CashPaidToIndividual> getCashPaidToIndividualSearchlist(CashPaidToIndividual info) throws Exception {
		openConnection();
		try {
			cashpaidtoindividualDAO = RemittanceDAOFactory.getCashPaidToIndividualDetailDAO(dbManager
				.getConnection());
		return cashpaidtoindividualDAO.getCashPaidToIndividualSearchlist(info);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public CashPaidToIndividualDataList findCashPaidToIndividualSearchlist(CashPaidToIndividualCri cri) throws Exception {
		openConnection();
		try {
			cashpaidtoindividualDAO = RemittanceDAOFactory.getCashPaidToIndividualDetailDAO(dbManager
					.getConnection());
			return cashpaidtoindividualDAO.findCashPaidToIndividualSearchlist(cri);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public CashPaidToIndividualDataList findCashPaidToIndividualSearchlist(CashPaidToIndividual cri) throws Exception {
		openConnection();
		try {
			cashpaidtoindividualDAO = RemittanceDAOFactory.getCashPaidToIndividualDetailDAO(dbManager
					.getConnection());
			return cashpaidtoindividualDAO.findCashPaidToIndividualSearchlist(cri);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	//Report
	public JasperPrint prepareCashPaidToIndividualReport(CashPaidToIndividualRpt info)
			throws Exception {
		openConnection();
		JasperPrint l_jsPrint = null;
		try {
			cashpaidtoindividualDAO = RemittanceDAOFactory.getCashPaidToIndividualDetailDAO(dbManager.getConnection());
			JRResultSetDataSource l_jrRS = new JRResultSetDataSource(cashpaidtoindividualDAO.prepareCashPaidToIndividualReport(info));
			JasperReport l_jsRpt = null;
			if(info.getOrderby().equals("currencyid"))
				l_jsRpt = (JasperReport) JRLoader
				.loadObjectFromFile(CommonSingleton.ABSOLUTE_PATH +"reports/CashPaidToIndividualByCurRpt.jasper");
			else
				l_jsRpt = (JasperReport) JRLoader
					.loadObjectFromFile(CommonSingleton.ABSOLUTE_PATH +"reports/CashPaidToIndividualRpt.jasper");
	
			HashMap<String, Object> l_params = new HashMap<String, Object>();
			l_params.put("companyname", "mbc");
			l_jsPrint = JasperFillManager.fillReport(l_jsRpt, l_params, l_jrRS);

		} catch (JRException je) {
			throw je;
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}

		return l_jsPrint;

	}
			
		public void gotoGL(CashPaidToIndividual l_entity, GL_STATUS status) throws Exception {
			
			currencyRateDAO = CommonDAOFactory.getCurrencyRateDAO(getConnection());
			branchCOADAO = RemittanceDAOFactory.getBranchCOADAO(getConnection());	
			generalCOADAO = RemittanceDAOFactory.getGeneral_COADAO(getConnection());
			agentCOADAO	= RemittanceDAOFactory.getAgentCOADAO(getConnection());
			agentDAO = RemittanceDAOFactory.getAgentDAO(getConnection());
			bankDAO = RemittanceDAOFactory.getBankDAO(getConnection());
			
			GeneralLedgerMgr l_glmgr = new GeneralLedgerMgr(this.sessionId);
			if(status == GL_STATUS.DELETE){
					l_glmgr.deleteGL(l_entity.getPaymentno() + "-PI");
			}
			if(status == GL_STATUS.CREATE) {
				if(l_entity.getFrombranchID() !=0)
				{
						BranchCOA l_branchCOA = branchCOADAO.findByHostBranchID(l_entity.getDefaultbranchID(), l_entity.getFrombranchID());
						General_COA l_generalCOA = generalCOADAO.find(l_entity.getDefaultbranchID());
						Bank l_Bank = new Bank();
						if(l_entity.getBranchId() != 0){
							l_Bank = bankDAO.findByCode(l_entity.getBankcode(), l_entity.getFrombranchID());
						}
					
					if(l_branchCOA == null)
						throw new DataNotFoundException("Plz fill BranchCOA", BranchCOA.class);
					
					GeneralLedger _glHeader = new GeneralLedger();
					_glHeader.setGlKey(l_glmgr.getGLKey());
					_glHeader.setSlip_ID(l_entity.getPaymentno() + "-PI");
					_glHeader.setSlipDate(l_entity.getTrdate());
					_glHeader.setSystemDate(new Date());
					_glHeader.setStatus("JH");
					_glHeader.setSrNo(1);
					_glHeader.setOffice_ID(l_entity.getDefaultbranchID());			
					
					l_glmgr.createGL(_glHeader);

					CurrencyRate l_currencyrate = currencyRateDAO.getCurrencyRateFromSourcetoHome(l_entity.getCurrencyID(), l_entity.getDefaultbranchID());
						GeneralLedger _glDebit = new GeneralLedger();
						_glDebit.setGlKey(l_glmgr.getGLKey());			
						_glDebit.setSlip_ID(l_entity.getPaymentno() + "-PI");
						_glDebit.setSlipDate(l_entity.getTrdate());
						_glDebit.setSystemDate(new Date());
						_glDebit.setCoaKey(l_branchCOA.getCurrentAccountID());
						_glDebit.setDepartmentKey(l_branchCOA.getDepartmentID());	
						_glDebit.setCurrencyKey(l_entity.getCurrencyID());
						_glDebit.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
						_glDebit.setExchangeRate(l_currencyrate.getRate());
						_glDebit.setSourceAmount(l_entity.getAmount());
						
						if(l_currencyrate.getRoper().equals("M"))
							_glDebit.setHomeAmount((l_entity.getAmount()) * l_currencyrate.getRate());
						else
							_glDebit.setHomeAmount((l_entity.getAmount() / l_currencyrate.getRate()));
						
						_glDebit.setStatus("JPI");	
						_glDebit.setSrNo(1);
						_glDebit.setOffice_ID(l_entity.getDefaultbranchID());			
						l_glmgr.createGL(_glDebit);		
						
						GeneralLedger _glCredit = new GeneralLedger();
						_glCredit.setGlKey(l_glmgr.getGLKey());	
						_glCredit.setSlip_ID(l_entity.getPaymentno() + "-PI");
						_glCredit.setSlipDate(l_entity.getTrdate());
						_glCredit.setSystemDate(new Date());
						if(l_entity.getBankID() == null){
							_glCredit.setCoaKey(l_generalCOA.getCashAccountID());
							_glCredit.setDepartmentKey(l_generalCOA.getCashDepartmentID());
						}else{
							_glCredit.setCoaKey(l_Bank.getCoaid());
							_glCredit.setDepartmentKey(l_Bank.getDepartmentid());
						}				
						_glCredit.setCurrencyKey(l_entity.getCurrencyID());
						_glCredit.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
						_glCredit.setExchangeRate(l_currencyrate.getRate());
						_glCredit.setSourceAmount(-(l_entity.getAmount()));
						
						if(l_currencyrate.getRoper().equals("M"))
							_glCredit.setHomeAmount(-(l_entity.getAmount() * l_currencyrate.getRate()));
						else
							_glCredit.setHomeAmount(-(l_entity.getAmount() / l_currencyrate.getRate()));
						
						_glCredit.setStatus("JPI");
						_glCredit.setSrNo(2);
						_glCredit.setOffice_ID(l_entity.getDefaultbranchID());
						
						l_glmgr.createGL(_glCredit);
					
				
						
				}
			else
				{
						Agent l_agent = agentDAO.findById(l_entity.getFromagentID());
						BranchCOA l_branchCOA = branchCOADAO.findByHostBranchID(l_entity.getDefaultbranchID(), l_entity.getDefaultbranchID());
						//AgentCOA l_agentCOA = agentCOADAO.findByCode(l_agent.getAccountset_code(), l_entity.getDefaultbranchID());
						General_COA l_generalCOA = generalCOADAO.find(l_entity.getDefaultbranchID());
						Bank l_Bank = new Bank();
						if(l_entity.getBankID() != null){
							
							 l_Bank = bankDAO.findByCode(l_entity.getBankcode(), l_entity.getDefaultbranchID());
						}
						
					
					if(l_branchCOA == null)
						throw new DataNotFoundException("Plz fill BranchCOA", BranchCOA.class);
					
					GeneralLedger _glHeader = new GeneralLedger();
					_glHeader.setGlKey(l_glmgr.getGLKey());	
					_glHeader.setSlip_ID(l_entity.getPaymentno() + "-PI");
					_glHeader.setSlipDate(l_entity.getTrdate());
					_glHeader.setSystemDate(new Date());
					_glHeader.setStatus("JH");
					_glHeader.setSrNo(1);
					_glHeader.setOffice_ID(l_entity.getDefaultbranchID());			

					l_glmgr.createGL(_glHeader);
					CurrencyRate l_currencyrate = currencyRateDAO.getCurrencyRateFromSourcetoHome(l_entity.getCurrencyID(), l_entity.getDefaultbranchID());
						GeneralLedger _glDebit = new GeneralLedger();
						_glDebit.setGlKey(l_glmgr.getGLKey());				
					_glDebit.setSlip_ID(l_entity.getPaymentno() + "-PI");
					_glDebit.setSlipDate(l_entity.getTrdate());
					_glDebit.setSystemDate(new Date());
						_glDebit.setCoaKey(l_branchCOA.getCurrentAccountID());
						_glDebit.setDepartmentKey(l_branchCOA.getDepartmentID());
						_glDebit.setCurrencyKey(l_entity.getCurrencyID());
						_glDebit.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
						_glDebit.setExchangeRate(l_currencyrate.getRate());
						_glDebit.setSourceAmount(l_entity.getAmount());
						
						if(l_currencyrate.getRoper().equals("M"))								
							_glDebit.setHomeAmount((l_entity.getAmount()) * l_currencyrate.getRate());
						else
							_glDebit.setHomeAmount((l_entity.getAmount() / l_currencyrate.getRate()));
					
					_glDebit.setStatus("JPI");	
					_glDebit.setSrNo(1);
						_glDebit.setOffice_ID(l_entity.getDefaultbranchID());			
						l_glmgr.createGL(_glDebit);		
						
						GeneralLedger _glCredit = new GeneralLedger();
						_glCredit.setGlKey(l_glmgr.getGLKey());
						_glCredit.setSlip_ID(l_entity.getPaymentno() + "-PI");
						_glCredit.setSlipDate(l_entity.getTrdate());
						_glCredit.setSystemDate(new Date());
						if(l_entity.getBankID() == 0){
							_glCredit.setCoaKey(l_generalCOA.getCashAccountID());
							_glCredit.setDepartmentKey(l_generalCOA.getCashDepartmentID());
						}else{
							_glCredit.setCoaKey(l_Bank.getCoaid());
							_glCredit.setDepartmentKey(l_Bank.getDepartmentid());
						}	
						_glCredit.setCurrencyKey(l_entity.getCurrencyID());
						_glCredit.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
						_glCredit.setExchangeRate(l_currencyrate.getRate());
						_glCredit.setSourceAmount(-(l_entity.getAmount()));
						
						if(l_currencyrate.getRoper().equals("M"))
							_glCredit.setHomeAmount(-(l_entity.getAmount() * l_currencyrate.getRate()));
						else
							_glCredit.setHomeAmount(-(l_entity.getAmount() / l_currencyrate.getRate()));
						
						_glCredit.setStatus("JPI");
						_glCredit.setSrNo(2);
						_glCredit.setOffice_ID(l_entity.getDefaultbranchID());
						
						l_glmgr.createGL(_glCredit);
					
				}
					
			}
		}
	public void UpdateCashPaid(STATUS Status,CashPaidToIndividual  entity) throws Exception {
		try {
			CashPaidToIndividual l_cpaid = new CashPaidToIndividual();
			cashpaidtoindividualDAO = RemittanceDAOFactory.getCashPaidToIndividualDetailDAO(dbManager.getConnection());
			
			if(entity.getFrombranchID()==0)
			{
					if(Status == STATUS.ADD){
				
					l_cpaid = new CashPaidToIndividual();
					
					l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamt(entity.getReceiptdetailid()).getPaidedamount());
					//l_cpaid.setPaidedamount(l_cpaid.getPaidedamount() + entity.getAmount());	
					l_cpaid.setPaidedamount((l_cpaid.getPaidedamount() == null) ? 0 :l_cpaid.getPaidedamount() + entity.getAmount());
					l_cpaid.setP_returnstatus((byte)2);
					l_cpaid.setReceiptdetailid(entity.getReceiptdetailid());
						cashpaidtoindividualDAO.updateCashPaid(l_cpaid);	
				}
				
				else if(Status == STATUS.UPDATE){
					
					l_cpaid = new CashPaidToIndividual();
					CashPaidToIndividual l_tempdetail = new CashPaidToIndividual();
					
					l_tempdetail = cashpaidtoindividualDAO.find(entity.getPaymentID());
					long tempreturndetailid = 0;
					long returndetailid =0 ;
					tempreturndetailid = l_tempdetail.getReceiptdetailid();
					returndetailid = entity.getReceiptdetailid();						
					
					if(tempreturndetailid != returndetailid ){			
						l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamt(l_tempdetail.getReceiptdetailid()).getPaidedamount());
						//l_cpaid.setPaidedamount(l_cpaid.getPaidedamount()-l_tempdetail.getAmount());	
						l_cpaid.setPaidedamount((l_cpaid.getPaidedamount() == null) ? 0 :l_cpaid.getPaidedamount()-l_tempdetail.getAmount());
						l_cpaid.setP_returnstatus((byte)0);					
						l_cpaid.setReceiptdetailid(l_tempdetail.getReceiptdetailid());
						cashpaidtoindividualDAO.updateCashPaid(l_cpaid);
						
						l_cpaid = new CashPaidToIndividual();
						l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamt(entity.getReceiptdetailid()).getPaidedamount());
						//l_cpaid.setPaidedamount(l_cpaid.getPaidedamount() +entity.getAmount());
						l_cpaid.setPaidedamount((l_cpaid.getPaidedamount() == null) ? 0 :l_cpaid.getPaidedamount() +entity.getAmount());	
						l_cpaid.setP_returnstatus((byte)2);
						l_cpaid.setReceiptdetailid(entity.getReceiptdetailid());
						cashpaidtoindividualDAO.updateCashPaid(l_cpaid);
					
					}
					else{
						l_cpaid = new CashPaidToIndividual();
						l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamt(entity.getReceiptdetailid()).getPaidedamount());
						//l_cpaid.setPaidedamount((l_cpaid.getPaidedamount()-l_tempdetail.getAmount()) + entity.getAmount());	
						l_cpaid.setPaidedamount(((l_cpaid.getPaidedamount() == null) ? 0 :l_cpaid.getPaidedamount()-l_tempdetail.getAmount()) + entity.getAmount());	
						l_cpaid.setP_returnstatus((byte)2);
						l_cpaid.setReceiptdetailid(entity.getReceiptdetailid());
						cashpaidtoindividualDAO.updateCashPaid(l_cpaid);
						
					}
				}
				else{
					l_cpaid = new CashPaidToIndividual();				
					l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamt(entity.getReceiptdetailid()).getPaidedamount());
					//l_cpaid.setPaidedamount(l_cpaid.getPaidedamount() - entity.getAmount());
					l_cpaid.setPaidedamount((l_cpaid.getPaidedamount() == null) ? 0 : l_cpaid.getPaidedamount() - entity.getAmount());
					l_cpaid.setP_returnstatus((byte)0);
					l_cpaid.setReceiptdetailid(entity.getReceiptdetailid());
					cashpaidtoindividualDAO.updateCashPaid(l_cpaid);
				}
		}
		else
		{
				if(Status == STATUS.ADD){
					
					l_cpaid = new CashPaidToIndividual();
					//if(entity.getStatus().equals("CraA"))
					if(entity.getReceiptdetailid()!=0)
						l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptdetailid(),entity).getPaidedamount());
					else
						l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptid(),entity).getPaidedamount());
					
					l_cpaid.setPaidedamount((l_cpaid.getPaidedamount() == null) ? 0 : l_cpaid.getPaidedamount() + entity.getAmount());	
					l_cpaid.setP_returnstatus((byte)2);
					l_cpaid.setReceiptdetailid(entity.getReceiptdetailid());
					//cashpaidtoindividualDAO.updateCashPaid(l_cpaid);
					l_cpaid.setReceiptid(entity.getReceiptid());
					
					cashpaidtoindividualDAO.UpdateCashPaidfromBranch(l_cpaid);
						
				}
				
				else if(Status == STATUS.UPDATE){
					
					l_cpaid = new CashPaidToIndividual();
					CashPaidToIndividual l_tempdetail = new CashPaidToIndividual();
					
					l_tempdetail = cashpaidtoindividualDAO.find(entity.getPaymentID());
					long tempreturndetailid = 0;
					long returndetailid =0 ;
					//tempreturndetailid = l_tempdetail.getReceiptid();
					//tempreturndetailid = l_tempdetail.getReceiptdetailid();
					//if(entity.getStatus().equals("CraA"))
					if(entity.getReceiptdetailid()!=0)
						{
							tempreturndetailid = l_tempdetail.getReceiptdetailid();
							returndetailid = entity.getReceiptdetailid();
						}
					else
						{
							returndetailid = entity.getReceiptid();
							tempreturndetailid = l_tempdetail.getReceiptid();
						}
						
					
					if(tempreturndetailid != returndetailid ){	
						if(entity.getReceiptdetailid()!=0)
							l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptdetailid(),entity).getPaidedamount());
						else
							l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptid(),entity).getPaidedamount());
							
						//	l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(l_tempdetail.getReceiptid(),entity.getStatus()).getPaidedamount());
						//l_cpaid.setPaidedamount(l_cpaid.getPaidedamount()-l_tempdetail.getAmount());	
						l_cpaid.setPaidedamount((l_cpaid.getPaidedamount() == null) ? 0 :l_cpaid.getPaidedamount()-l_tempdetail.getAmount());
						l_cpaid.setP_returnstatus((byte)0);	
						if(entity.getReceiptdetailid()!=0)
							l_cpaid.setReceiptdetailid(l_tempdetail.getReceiptdetailid());
						else
							l_cpaid.setReceiptid(l_tempdetail.getReceiptid());
						
						cashpaidtoindividualDAO.UpdateCashPaidfromBranch(l_cpaid);
						
						l_cpaid = new CashPaidToIndividual();
						l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptid(),entity).getPaidedamount());
						//l_cpaid.setPaidedamount(l_cpaid.getPaidedamount() +entity.getAmount());
						l_cpaid.setPaidedamount((l_cpaid.getPaidedamount() == null) ? 0 :l_cpaid.getPaidedamount() +entity.getAmount());	
						l_cpaid.setP_returnstatus((byte)2);
						l_cpaid.setReceiptdetailid(entity.getReceiptdetailid());
						l_cpaid.setReceiptid(entity.getReceiptid());
						cashpaidtoindividualDAO.UpdateCashPaidfromBranch(l_cpaid);
					
					}
					else{
						l_cpaid = new CashPaidToIndividual();
						if(entity.getReceiptdetailid()!=0)
							l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptdetailid(),entity).getPaidedamount());
						else
							l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptid(),entity).getPaidedamount());
							
						//l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptid(),entity.getStatus()).getPaidedamount());
						l_cpaid.setPaidedamount((l_cpaid.getPaidedamount() == null) ? 0 : l_cpaid.getPaidedamount()-l_tempdetail.getAmount() + entity.getAmount());
						//l_cpaid.setPaidedamount((l_cpaid.getPaidedamount()-l_tempdetail.getAmount()) + entity.getAmount());	
						l_cpaid.setP_returnstatus((byte)2);
						l_cpaid.setReceiptdetailid(entity.getReceiptdetailid());
						l_cpaid.setReceiptid(entity.getReceiptid());
						cashpaidtoindividualDAO.UpdateCashPaidfromBranch(l_cpaid);
						
					}
				}
				else{
					l_cpaid = new CashPaidToIndividual();
					if(entity.getReceiptdetailid()!=0)
						l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptdetailid(),entity).getPaidedamount());
					else
						l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptid(),entity).getPaidedamount());
						
					//l_cpaid.setPaidedamount(cashpaidtoindividualDAO.findpaidamtfrombranch(entity.getReceiptid(),entity.getStatus()).getPaidedamount());
					//l_cpaid.setPaidedamount(l_cpaid.getPaidedamount() - entity.getAmount());
					l_cpaid.setPaidedamount((l_cpaid.getPaidedamount() == null) ? 0 :l_cpaid.getPaidedamount() - entity.getAmount());
					l_cpaid.setP_returnstatus((byte)0);
					l_cpaid.setReceiptdetailid(entity.getReceiptdetailid());
					l_cpaid.setReceiptid(entity.getReceiptid());
					cashpaidtoindividualDAO.UpdateCashPaidfromBranch(l_cpaid);
				}
		}
		} catch(Exception e) { throw e; }
		/* -- END GL ADD DATA -- */
	} 
	
}
	
			
	





